package wx

/**
 * 使用用户第三方调用的接口
 */
type UserTokenInfo struct {
	AccessToken  string `json:"access_token"`  // "36_Qm3qAVTXZQjbI0sAwUCic9Z4mQQlOreWRXGbg-SThA7oPiYu2HZzW4PRSiKu0cQpNoyE573fv74udjUcFksqsg"
	ExpiresIn    int64  `json:"expires_in"`    // 7200
	RefreshToken string `json:"refresh_token"` // "36_FJNG-sbRs28ebXZUwwc6J4whH1KddnvSltirLTRW6RFpXWmOoTSqYcQi0CBD90SXJgF98Da_vgfzgbya7HJz6A"
	OpenID       string `json:"openid"`        // "o6HBW0Ym5nE4kQ--kQIwhbSoCXGs"
	Scope        string `json:"scope"`         // "snsapi_base" / "snsapi_userinfo"
}

// 使用code拉取用户token
func FetchUserToken(code string) (UserTokenInfo, error) {
	data := struct {
		ErrInfo
		UserTokenInfo
	}{}
	err := Get("https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code", map[string]string{
		"appid":  appid,
		"secret": secret,
		"code":   code,
	}, &data)
	return data.UserTokenInfo, err
}

// 拉取用户信息，需要获取许可
func FetchUserInfoByUserToken(token string, openid string) (UserInfo, error) {
	data := struct {
		ErrInfo
		UserInfo
	}{}
	err := Get("https://api.weixin.qq.com/sns/userinfo?lang=zh_CN", map[string]string{
		"access_token": token,
		"openid": openid,
	}, &data)
	return data.UserInfo, err
}